package webapiframework

import (
	"fmt"
	"io/ioutil"
	"net/http"
	"os"
	"path/filepath"
	"photoPlugIn/config"
	us "photoPlugIn/utils"
)

var Router *RouterHandler = new(RouterHandler)

type RouterHandler struct {
}

var mux = make(map[string]func(http.ResponseWriter, *http.Request))

func (p *RouterHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	fmt.Println(r.URL.Path)
	fun, ok := mux[r.URL.Path]
	if ok {
		fun(w, r)
		return
	}
	rUrl := r.URL.String()
	if len(rUrl) > 9 && rUrl[0:9] == "/photoDB/" {

		rUrl = rUrl[1:]
		rUrl, err := filepath.Abs(config.CONFIG.CacheDir + config.CONFIG.PHOTODB + "/" + rUrl[8:])
		fmt.Println("rUrl", rUrl)
		us.CheckErr(err)
		isURL, _ := us.PathExists(rUrl, false)
		if isURL {
			file, err := os.Open(rUrl)
			defer file.Close()
			if err != nil {
				fmt.Println("static resource:", err)
				w.WriteHeader(404)
				http.Error(w, "error URL:"+r.URL.String(), http.StatusBadRequest)
			} else {
				bs, _ := ioutil.ReadAll(file)
				w.Header().Set("Content-Type", "image/jpg")

				w.Write(bs)
				return
			}
		}
	}
	//启用简单的SimpleWebServer
	if config.CONFIG.SimpleWebServer {

		rUrl = rUrl[1:]

		rUrl, err := filepath.Abs(config.CONFIG.WebServerRoot + rUrl)
		us.CheckErr(err)
		isURL, _ := us.PathExists(rUrl, false)

		if isURL {
			file, err := os.Open(rUrl)
			defer file.Close()
			if err != nil {
				fmt.Println("static resource:", err)
				w.WriteHeader(404)
				http.Error(w, "error URL:"+r.URL.String(), http.StatusBadRequest)
			} else {
				bs, _ := ioutil.ReadAll(file)
				fmt.Println("filepath.Ext(rUrl)", filepath.Ext(rUrl))
				if filepath.Ext(rUrl) == ".css" {
					w.Header().Set("Content-Type", "text/css;charset=utf-8")
				} else if filepath.Ext(rUrl) == ".js" {
					w.Header().Set("Content-Type", "application/javascript;charset=utf-8")
				} else {
					w.Header().Set("Content-Type", "text/html;charset=utf-8")
				}

				w.Write(bs)
			}
			return
		}
	}

	http.Error(w, "error URL:"+r.URL.String(), http.StatusBadRequest)

}
func (p *RouterHandler) Router(relativePath string, handler func(http.ResponseWriter, *http.Request)) {
	mux[relativePath] = handler
}
